const toTree = function(arr1) {
  const arr = deepClone(arr1)
  const tree = []
  findChildren(arr, null, tree)
  return tree.children
}
function findChildren(arr, id, tree) {
  for(var i = 0; i < arr.length; i++){
    if(arr[i].children == undefined) {
      arr[i].children = []
    }
    if(arr[i].pId == id) {
        if(tree.children == undefined) {
            tree.children = []
        }
        tree.children.push(arr[i])
        findChildren(arr, arr[i].id, tree.children[tree.children.length-1])
    }
  }
}

//返回传递给他的任意对象的类
const isClass = (o) => {
    if (o === null) return "Null"
    if (o === undefined) return "Undefined"
    return Object.prototype.toString.call(o).slice(8, -1)
  }
//深度克隆
const deepClone = (obj) => {
    if (!obj) { return null }
    let result, oClass = isClass(obj)
    //确定result的类型
    if (oClass === "Object") {
      result = {}
    } else if (oClass === "Array") {
      result = []
    } else {
      return obj
    }
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        let copy = obj[key]
        if (isClass(copy) == "Object") {
          result[key] = deepClone(copy)//递归调用
        } else if (isClass(copy) == "Array") {
          result[key] = deepClone(copy)
        } else {
          result[key] = obj[key]
        }
      }
    }
    return result
  }
export default toTree